package com.yiren.dbaa.module.common.view.activity;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.BrightnessUtils;
import com.blankj.utilcode.util.VolumeUtils;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.config.enums.LocationTypeEnum;
import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.constant.DateTimeConstant;
import com.yiren.backstage.currency.constant.DbConstant;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.currency.enums.GpsStateEnum;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.activity.BaseActivity;
import com.yiren.dbaa.constant.G;
import com.yiren.dbaa.constant.SendParamConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.currency.dialog.CommonDialog;
import com.yiren.dbaa.module.common.bean.LoginQrcodeBean;
import com.yiren.dbaa.module.common.contract.MainContract;
import com.yiren.dbaa.module.common.presenter.MainPresenter;
import com.yiren.dbaa.module.common.view.dialog.LoginDialog;
import com.yiren.dbaa.module.common.view.dialog.RiskControlDialog;
import com.yiren.dbaa.module.device.contract.DeviceConnectContract;
import com.yiren.dbaa.module.exam.view.activity.ExamDjActivity;
import com.yiren.dbaa.module.help_center.api.IHardwareUpdate;
import com.yiren.dbaa.module.help_center.api.ISoftUpdate;
import com.yiren.dbaa.module.help_center.api.impl.HardwareUpdateImpl;
import com.yiren.dbaa.module.help_center.api.impl.SoftUpdateImpl;
import com.yiren.dbaa.module.help_center.view.activity.AfterServiceActivity;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.module.practice_set.PracticeCarSetActivity;
import com.yiren.dbaa.net.rtk.BaseStationHelper;
import com.yiren.dbaa.util.BDLocationUtil;
import com.yiren.dbaa.util.DeviceUtil;
import com.yiren.dbaa.util.NetWorkUtil;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lwb
 * @date : 2022/7/4 13:43
 * @description: 首页
 */
public class MainActivity extends BaseActivity implements MainContract.View, DeviceConnectContract.View {

    @BindView(R.id.tv_network)
    TextView tvNetwork;
    @BindView(R.id.tv_host)
    TextView tvHost;
    @BindView(R.id.tv_bei_dou)
    TextView tvBeiDou;
    @BindView(R.id.tv_brightness)
    TextView tvBrightness;
    @BindView(R.id.tv_volume)
    TextView tvVolume;
    @BindView(R.id.iv_coach_icon)
    ImageView ivCoachIcon;
    @BindView(R.id.tv_coach_name)
    TextView tvCoachName;
    @BindView(R.id.tv_soft_ver)
    TextView tvSoftVer;
    @BindView(R.id.tv_hardware_ver)
    TextView tvHardwareVer;
    @BindView(R.id.tv_device_number)
    TextView tvDeviceNumber;

    private MainContract.Presenter mainPresenter;
    private ISoftUpdate iSoftUpdate;
    private IHardwareUpdate iHardwareUpdate;
    private UserParamConfigBean userParamConfig;
    private LoginDialog loginDialog;

    private Intent intent;
    /*** 是否需要重新登录 */
    private boolean isLogOut;
    private Handler handler;
    private Runnable homeRunnable;
    /*** 教练扫码页面是否显示 */
    private boolean isShowCoachQrCode;
    /*** 教练二维码标识码 */
    private String code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initData();
        setData();
        refresh();
        if (G.isFirstStartApp) {
            new BaseStationHelper(this).get4GInfoData(true);
            G.isFirstStartApp = false;
        }
    }

    private void initData() {
        intent = getIntent();
        isLogOut = intent.getBooleanExtra("isLogOut", false);
        BDLocationUtil bdLocationUtil = new BDLocationUtil(this);
        bdLocationUtil.startGpsListenForInMode();
        mainPresenter = new MainPresenter(this);
        iSoftUpdate = new SoftUpdateImpl(this);
        userParamConfig = LoadConfigApi.loadUserParamConfig(this);
        iHardwareUpdate = new HardwareUpdateImpl(this);
        loginDialog = new LoginDialog(this, mainPresenter);
        handler = new Handler();
    }

    private void setData() {
        tvSoftVer.setText(DeviceUtil.getAppVersion(this));
        if (null != userParamConfig.getUserInfo()) {
            ivCoachIcon.setImageResource(R.mipmap.coach_login);
            tvCoachName.setText(userParamConfig.getUserInfo().getPhone());
        } else {
            ivCoachIcon.setImageResource(R.mipmap.coach_icon);
            tvCoachName.setText("教练登录");
        }
        if (isLogOut) {
            mainPresenter.getCoachLoginQrCode(this);
        }
        mainPresenter.getDeviceNumber(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setResumeData();
//        iCheckSoftUpdate.checkSoftUpdate(false);
//        iCheckHardwareUpdate.checkSystemUpdate(false);
    }

    /**
     * 设置页面可见需要刷新的数据
     */
    private void setResumeData() {
        userParamConfig = LoadConfigApi.loadUserParamConfig(this);
        //设置User.db的路径
        mainPresenter.verifyUserDb();
    }

    @OnClick({R.id.ll_network, R.id.ll_bei_dou, R.id.ll_brightness, R.id.ll_volume, R.id.ll_exam_system, R.id.ll_light_special, R.id.ll_play_system, R.id.ll_coach_login, R.id.ll_help_center, R.id.ll_pra_set})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_network:
                if (android.os.Build.VERSION.SDK_INT > 10) {
                    // 3.0以上打开设置界面，也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面
                    startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
                } else {
                    startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                }
                break;
            case R.id.ll_bei_dou:    //北斗卫星
                mainPresenter.showPopWindowSatellites(tvBeiDou);
                break;
            case R.id.ll_brightness:  //屏幕亮度
                startActivity(new Intent(Settings.ACTION_DISPLAY_SETTINGS));
                break;
            case R.id.ll_volume:      //音量
                AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_SAME, AudioManager.FLAG_SHOW_UI);
                break;
            case R.id.ll_exam_system:
                enterExam(SendParamConstant.ZDPP_MODEL);
                break;
            case R.id.ll_light_special:   //灯光专项

                break;
            case R.id.ll_play_system: //播报系统
                enterExam(SendParamConstant.ZDBB_MODEL);
                break;
            case R.id.ll_coach_login: //教练登录
                if (null != userParamConfig.getUserInfo()) {
                    loginDialog.showAlreadyLoginDialog(userParamConfig.getUserInfo().getPhone(), new CommonCallBack() {
                        @Override
                        public void complete() {
                            mainPresenter.getCoachLoginQrCode(MainActivity.this);
                        }
                    });
                } else {
                    mainPresenter.getCoachLoginQrCode(this);
                }
                break;
            case R.id.ll_help_center:
                startActivity(new Intent(this, AfterServiceActivity.class));
                break;
            case R.id.ll_pra_set:
                if (null == userParamConfig.getUserInfo()) {
                    MessageBox.show(this, "设备未登录，请先登录！");
                    return;
                }
                if (mainPresenter.verifyUserDb()) {
                    startActivity(new Intent(this, PracticeCarSetActivity.class));
                } else {
                    MessageBox.show(this, "用户文件丢失，请重新登录！");
                }
                break;
        }
    }

    /**
     * 进入考试页面
     *
     * @param model
     */
    private void enterExam(String model) {
        if (null == userParamConfig.getUserInfo()) {
            MessageBox.show(this, "教练未登录，请先登录！");
            return;
        }
        if (null == userParamConfig.getSite()) {
            List<SiteEntity> localSites = UserDbController.getInstance(false).queryAll(SiteEntity.class);
            if (null != localSites && localSites.size() > 0) {
                userParamConfig.setSite(localSites.get(0));
                ParamConfigApi.saveUserParamConfig(this, userParamConfig);
            } else {
                showDownLoadSiteDialog();
                return;
            }
        }
        if (mainPresenter.verifyUserDb()) {
            mainPresenter.prepareExam(model, this);
        } else {
            MessageBox.show(this, "用户文件丢失，请重新登录！");
        }
    }

    /**
     * 显示去下载考场数据对话框
     */
    private void showDownLoadSiteDialog() {
        CommonDialog.showOneBtn(this, "温馨提示", "暂无考场数据，请先下载考场数据", "去下载", (dialog, which) -> {
            dialog.dismiss();
            if (mainPresenter.verifyUserDb()) {
                startActivity(new Intent(this, PracticeCarSetActivity.class));
            } else {
                MessageBox.show(this, "用户文件丢失，请重新登录！");
            }
        });
    }

    /**
     * 刷新首页状态
     */
    private void refresh() {
        homeRunnable = () -> {
            setRefreshData();
            handler.postDelayed(homeRunnable, 1000);
        };
        handler.post(homeRunnable);
    }

    /**
     * 设置刷新数据
     */
    private void setRefreshData() {
        //设置主机状态
        if (null != G.connectDeviceMessage) {
            setTextAndColor(tvHost, "已连接", 1);
            tvHardwareVer.setText(G.connectDeviceMessage.getVersionDescribe());
        } else {
            setTextAndColor(tvHost, "未连接", 2);
            tvHardwareVer.setText("");
        }
        //设置网络状态
        if (NetWorkUtil.isNetworkAvailable(this)) {
            setTextAndColor(tvNetwork, "已连接", 1);
        } else {
            setTextAndColor(tvNetwork, "未连接", 2);
        }
        //设置北斗定位
        GpsInfoBean gps = GpsInfoBean.getInstance();
        if (userParamConfig.isHasGjdInterface()) {
            //差分定位数据不为空时显示高精度，外置GPS数据不为空时显示外置北斗
            if (!"".equals(SignalGConstant.cfGpsData)) {
                //定位+定向 成功才显示高精度定位成功
                if (gps.getStatusPosition() == 3 && gps.getStatusDirection() == 3) {
                    setTextAndColor(tvBeiDou, "高精度定位成功", 1);
                } else {
                    setTextAndColor(tvBeiDou, "高精度定位中", 2);
                }
            } else {
                if (System.currentTimeMillis() - DateTimeConstant.gpsRetTime > DateTimeConstant.GPS_TIME_GAP) {
                    setTextAndColor(tvBeiDou, "高精度未连接", 2);
                } else {
                    if (gps.getExternalLocationState() == GpsStateEnum.LOCATION_SUCCESS) {
                        setTextAndColor(tvBeiDou, "外置北斗定位成功", 1);
                    } else {
                        setTextAndColor(tvBeiDou, "外置北斗定位中", 2);
                    }
                }
            }
        } else {
            //GPS信号，如果是内置GPS就显示为内置GPS，如果使用的外置GPS，则需要显示是否连接GPS线
            if (LoadConfigApi.loadSignalSourceConfig(this).getLocationType().equals(LocationTypeEnum.BUILT_IN)) {
                if (gps.getInternalLocationState() == GpsStateEnum.LOCATION_SUCCESS) {
                    setTextAndColor(tvBeiDou, "内置北斗定位成功", 1);
                } else {
                    setTextAndColor(tvBeiDou, "内置北斗定位中", 2);
                }
            } else {
                if (System.currentTimeMillis() - DateTimeConstant.gpsRetTime > DateTimeConstant.GPS_TIME_GAP) {
                    setTextAndColor(tvBeiDou, "外置北斗未连接", 2);
                } else {
                    if (gps.getExternalLocationState() == GpsStateEnum.LOCATION_SUCCESS) {
                        setTextAndColor(tvBeiDou, "外置北斗定位成功", 1);
                    } else {
                        setTextAndColor(tvBeiDou, "外置北斗定位中", 2);
                    }
                }
            }
        }
        //设置亮度
        tvBrightness.setText(BrightnessUtils.getBrightness() + "");
        //设置声音
        tvVolume.setText(VolumeUtils.getVolume(AudioManager.STREAM_MUSIC) + "");
    }

    /**
     * 设置TextView的文本和颜色
     */
    private void setTextAndColor(TextView tv, String txt, int color) {
        tv.setText(txt);
        tv.setTextColor(color == 1 ? getResources().getColor(R.color.main_green) : getResources().getColor(R.color.dbaf_ff5047));
    }

    @Override
    public void showEquipmentIdState(String equipmentId) {
        tvDeviceNumber.setText(equipmentId);
    }

    @Override
    public void showNoSiteDataDialog() {
        CommonDialog.showOneBtn(this, "温馨提示", "未下载考场数据，请先下载考场数据！", "去下载", (dialog, which) -> {
            dialog.dismiss();
            startActivity(new Intent(this, PracticeCarSetActivity.class));
        });
    }

    @Override
    public void showRiskControlDialog(String examModel, int type, String reason, String url) {
        if (type == 0) {  //没有风控限制
            intent = new Intent(this, ExamDjActivity.class);
            intent.putExtra(SendParamConstant.EXAM_MODEL, examModel);
            startActivity(intent);
        } else {
            RiskControlDialog.showDeviceUnuseDialog(this, type, reason, url, v -> {
                mainPresenter.getDeviceRiskResult();
            });
        }
    }

    @Override
    public void setCoachLoginQrCode(LoginQrcodeBean coachQrCodeBean) {
        code = coachQrCodeBean.getCode();
        isShowCoachQrCode = true;
        loginDialog.showCoachLoginDialog(coachQrCodeBean.getUrl(), new CommonCallBack() {
            @Override
            public void complete() {
                isShowCoachQrCode = false;
            }
        });
        checkCoachSweepCode(code);
    }

    @Override
    public void coachLoginComplete() {
        isShowCoachQrCode = false;
        loginDialog.closeCoachLoginDialog();
    }

    @Override
    public void coachLoginFail(String error) {
        CommonDialog.showOneBtn(this, "温馨提示", error, "我知道了", (dialog, which) -> {
            dialog.dismiss();
        });
    }

    @Override
    public void checkCoachSweepCode() {
        checkCoachSweepCode(code);
    }

    @Override
    public void getUserInfoSuccess() {
        userParamConfig = LoadConfigApi.loadUserParamConfig(this);
        ivCoachIcon.setImageResource(R.mipmap.coach_login);
        tvCoachName.setText(userParamConfig.getUserInfo().getPhone());
        mainPresenter.getDeviceNumber(this);
    }

    /**
     * 检测教练扫码
     *
     * @param code
     */
    private void checkCoachSweepCode(String code) {
        if (!isShowCoachQrCode) return;
        if (StringUtils.isEmpty(code)) return;
        mainPresenter.checkCoachSweepCode(code, this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != homeRunnable) {
            handler.removeCallbacks(homeRunnable);
        }
        mainPresenter.removeAllCallBack();
    }

    @Override
    public void deviceConnectSuccess() {
        MessageBox.show(this, "设备连接成功!");
    }
}